/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ex.util.generator;

import ex.datatypes.TaxiRide;
import ex.util.MyBatisUtils;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.PriorityQueue;

/**
 * This SourceFunction generates a data stream of TaxiRide records.
 *
 * <p>The stream is produced out-of-order.
 */
public class TaxiRideGeneratorFromMysql implements SourceFunction<TaxiRide> {

    private volatile boolean running = true;

    @Override
    public void run(SourceContext<TaxiRide> ctx) throws Exception {
        //从数据库查询TaxiRide
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        String sqlId = "ex.springboot.mapper.TaxiRideMapper.selectTaxiRides";
        List<TaxiRide> dbTaxiRides = sqlSession.selectList(sqlId);
        sqlSession.close();

        while (running) {

            //生成一批START事件
            for (int i = 1; i < dbTaxiRides.size(); i++) {
                TaxiRide ride = dbTaxiRides.get(i);
                ctx.collect(ride);
                Thread.sleep(1000);
            }
            if(dbTaxiRides.size()==10){
                running=false;
            }

        }
    }

    @Override
    public void cancel() {
        running = false;
    }
}
